//
//  WebManager.swift
//  ToBeBigFE
//
//  Created by mingo on 2020/2/24.
//  Copyright © 2020 com.example. All rights reserved.
//

import Foundation

/*
管理项目化之后的逻辑:
1. manifest.json
2. 正式的url的拼接
 */
class WebManager {
    
    // 单例模式
    public static let shared = WebManager()
    
    public let settings = UserDefaults(suiteName: "WebDev")!
    
    // 项目名 => 版本
    private var versionDict = [String:String]()
    
    // 初始化
    init() {
        // 读取解析manifest.json的过程
        let path = Bundle.main.path(forResource: "manifest", ofType: "json")!
        let data = FileManager.default.contents(atPath: path)!
        let json = try! JSONSerialization.jsonObject(with: data, options: []) as! [String:Any?]
        let projects = json["projects"] as! [[String:Any?]]
        projects.forEach { item in
            versionDict[item["name"] as! String] = item["version"] as? String
        }
    }
    
    // 根据id和page获取正式的url
    func getWebUrl(id: String, page: String) -> String {
        
        if settings.bool(forKey: "enabled"),
            let server = settings.string(forKey: "server"),
            let project = settings.string(forKey: "project"),
            project == id
        {
            return "http://\(server)/\(project)/dev/\(page)"
        }
        
        let version = versionDict[id] ?? "1"
        return "\(WebConst.WEB_BASE_URL)\(id)/\(version)/\(page)"
    }
    
}
